package controllers

import (
	"fmt"
	"strings"
	"net/http"
	"meman/models/auth"
	"github.com/labstack/echo"
	"github.com/chaosue/echo-sessions"
	"meman/sys/basic"
)


const USER_INFO_SESSION_KEY = "userInfo"

/**
用户中间件,验证是否登录,是否存在session
 */
func AuthMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
	return func(c echo.Context) error {
		session := sessions.Default(c)
		user,ok := session.Get(USER_INFO_SESSION_KEY).(*auth.User)
		if !strings.Contains(c.Request().URL().Path(), "/Auth/Login")  && user == nil && ok == false {
			loginUrl := fmt.Sprintf("%s%s/?camefrom=%s", basic.Config.Auth.BaseUrl, basic.Config.Auth.LoginPath, basic.Config.Auth.AppName)
			c.Redirect(http.StatusFound, loginUrl)
		}else {
			if err := next(c); err != nil {
				return err
			}
		}
		return nil
	}
}


/**
登录
 */
func Login(c echo.Context) error  {
	token := c.QueryParam("token")
	//loginUrl := c.Query("login_url")
	username := c.QueryParam("username")

	if token == "" || username == "" {
		c.Render(http.StatusOK, "errors.tmpl", basic.H{
			"errorMessage": "Auth登录: token或username为空",
		})
	}
	session := sessions.Default(c)
	auth := auth.Auth{}
	user,err := auth.Login(token, username)
	if err != nil {
		c.Render(http.StatusOK, "errors.tmpl", basic.H{
			"errorMessage": err.Error(),
		})
	}else {
		session.Set(USER_INFO_SESSION_KEY, user)
		session.Save()
	}

	//需要重定向回主页
	c.Redirect(http.StatusFound,"/")

	return nil

}

/**
退出
 */
func LoginOut(c echo.Context) error  {
	session := sessions.Default(c)
	session.Delete(USER_INFO_SESSION_KEY)
	session.Save()

	//需要重定向回主页
	c.Redirect(http.StatusFound,"/")

	return nil
}
